from app import db
from datetime import datetime
from sqlalchemy.orm import foreign

class DataUpload(db.Model):
    __tablename__ = 'data_uploads'
    
    id = db.Column(db.BigInteger, primary_key=True)
    user_id = db.Column(db.BigInteger, nullable=False)
    file_name = db.Column(db.String(255), nullable=False)
    original_file_name = db.Column(db.String(255), nullable=False)
    file_size = db.Column(db.BigInteger, nullable=False)
    file_type = db.Column(db.String(50), nullable=False)
    file_content = db.Column(db.LargeBinary(length=4294967295), nullable=True)  # 使用LONGBLOB类型，最大4GB
    upload_time = db.Column(db.DateTime, default=datetime.utcnow)
    status = db.Column(db.Enum('processing', 'completed', 'failed'), default='processing')
    error_message = db.Column(db.Text)
    
    # 关系
    summaries = db.relationship('Summary', 
                               primaryjoin="DataUpload.id == foreign(Summary.upload_id)",
                               backref='upload', lazy=True, cascade="all, delete-orphan")
    
    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'file_name': self.file_name,
            'original_file_name': self.original_file_name,
            'file_size': self.file_size,
            'file_type': self.file_type,
            'upload_time': self.upload_time.isoformat(),
            'status': self.status,
            'error_message': self.error_message,
            'summary_count': len(self.summaries) if self.summaries else 0,
            'has_content': self.file_content is not None
        }

class Summary(db.Model):
    __tablename__ = 'summaries'
    
    id = db.Column(db.BigInteger, primary_key=True)
    upload_id = db.Column(db.BigInteger, nullable=False)
    fname = db.Column(db.String(255))
    dialogue = db.Column(db.Text, nullable=False)
    summary = db.Column(db.Text, nullable=False)
    keywords = db.Column(db.Text)
    coreference_id = db.Column(db.String(255))
    coreference_text = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': self.id,
            'upload_id': self.upload_id,
            'fname': self.fname,
            'dialogue': self.dialogue,
            'summary': self.summary,
            'keywords': self.keywords,
            'coreference_id': self.coreference_id,
            'coreference_text': self.coreference_text,
            'created_at': self.created_at.isoformat()
        } 